package org.gd.hellojaxb.adapters;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class SecureCardXmlAdapter extends XmlAdapter<String, String> {

    private static final int LENGTH = 4;

    @Override
    public String unmarshal(String v) throws Exception {
        if(v == null || v.isEmpty()) {
            return v;
        }
        return v.replace(" ", "");
    }

    @Override
    public String marshal(String v) throws Exception {
        if(v == null || v.isEmpty()) {
            return v;
        }
        StringBuilder card = new StringBuilder();
        card.append(v.substring(0, LENGTH));
        for(int i=0; i<v.length()-LENGTH*2; i++) {
            card.append("*");
        }
        return card.append(v.substring(v.length()-LENGTH, v.length()))
                .toString();
    }
}
